package com.yc.thread.basic;

/**
 * 在A线程通过一个变量控制B线程的运行
 * @author zwei
 * @create 2024-07-16 14:31
 */
public class Test18_volatile {
    public static void main(String[] args) {
        Task task=new Task();
        Thread thread1=new Thread(task,"线程A");
        thread1.start();

        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    System.out.println("线程B中改变  stop的值为true  以停止线程A");
                    task.stop=true;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        },"线程B");
        thread2.start();
    }
}
class Task implements Runnable{
    volatile boolean stop=false;    //内存可见性
    int i=0;
    @Override
    public void run() {
        long start=System.currentTimeMillis();
        while (!stop){
            i++;
        }
        System.out.println(i);
        System.out.println(stop);
        System.out.println("线程退出，运行时间："+(System.currentTimeMillis()-start));
    }
}
